package cn.ze.yygh.msm.controller;

import cn.ze.yygh.common.result.Result;
import cn.ze.yygh.msm.service.MsmService;
import cn.ze.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplatel;

    //发送手机验证码
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //从redis中获取验证码,如果获取到 返回ok
        String code = redisTemplatel.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) return Result.ok();

        //如果从redis中获取不到
        //生成二维码 通过整合短信服务进行发送
        code = RandomUtil.getSixBitRandom();
        boolean isSend = msmService.send(phone,code);
        //TODO  短信或者邮箱发送这个code
        //暂时直接打印查看
        System.out.println(code);
        //短信是否发送成功

        //生成的验证码放入redis  设置有效时间
        if (isSend) {
            redisTemplatel.opsForValue().set(phone, code, 3, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail("发送短信失败");
        }

    }

}
